<template>
  <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
    <el-form-item label="轮播图链接" prop="link">
      <el-input v-model="ruleForm.link" autocomplete="off" />
    </el-form-item>
    <el-form-item label="轮播图提示" prop="alt">
      <el-input v-model="ruleForm.alt" autocomplete="off" />
    </el-form-item>
    <el-form-item label="图片地址" prop="img">
      <el-input v-model.number="ruleForm.img" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">新增图片</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElNotification } from 'element-plus'
import service from '@/utils/service';

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
  link: '',
  alt: '',
  img: '',
})

const rules = reactive<FormRules>({
  link: [{ required: true, message: '请输入轮播图连接', trigger: 'blur' }],
  alt: [{ required: true, message: '请输入轮播图提示', trigger: 'blur' }],
  img: [{ required: true, message: '请输入图片地址', trigger: 'blur' }],
})

const emit = defineEmits()

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: any) => {
    if (valid) {
      // 添加轮播图
      service({
        url: '/admin/banner/add',
        method: 'post',
        data: {
          img: ruleForm.img,
          alt: ruleForm.alt,
          link: ruleForm.link
        }
      }).then((res: any) => {
        if (res.data.code === '200') {
          ElNotification({
            message: '添加轮播图成功！',
            type: 'success',
          })
          emit('success')
          ruleForm.img = ''
          ruleForm.alt = ''
          ruleForm.link = ''
        }
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style></style>